#!/bin/bash

function file_exist
{
    local file_name
    if [ $# -ne 1 ];then
        return ${RET_ERR}
    fi

    file_name=$1
    if [ -e $file_name -a ! -d $file_name ];then
        return ${RET_OK}
    else
        return ${RET_ERR}
    fi
}

function file_executable
{
    local file_name
    if [ $# -ne 1 ];then
        return ${RET_ERR}
    fi
    
    file_name=$1
    if [ -x $file_name -a ! -d $file_name ];then
        return ${RET_OK}
    else
        return ${RET_ERR}
    fi
}

function check_proc_exist
{
    local proc_name proc_port port_name
    if [ $# -eq 2 -a $2 -gt 0 2>/dev/null ];then
        proc_name=$1
        proc_port=$2
        port_name=`/usr/sbin/lsof -P -i :$proc_port |grep "*:$proc_port\>"|awk '{print $1}'|uniq`
        if [ "$proc_name" = "$port_name" ];then
            return ${RET_OK}
        else
            return ${RET_ERR}
        fi
    elif [ $# -eq 1 ];then
        proc_name=$1
        pstree -pl|grep "\-${proc_name}([0-9].*)" &>/dev/null
        if [ $? -eq 0 ];then
            return ${RET_OK}
        else
            return ${RET_ERR}
        fi  
    else
        return ${RET_ERR}
    fi
}

function check_proc_num
{
    local proc_num proc_name real_num
    if [ $# -eq 2 -a $2 -gt 0 2>/dev/null ];then
        proc_name=$1
        proc_num=$2
    else
        return ${RET_ERR}
    fi

    real_num=`pstree -pl|grep "\-[{]\{0,1\}${proc_name}[}]\{0,1\}([0-9].*)"|wc -l |awk '{print$1}'`
    if [ $real_num -ge $proc_num ];then
        return ${RET_OK}
    else
        return ${RET_ERR}
    fi
}

function check_log_roll
{
    local time_limit log_name i this_time last_time
    if [ $# -ne 2 ];then
        return ${RET_ERR}
    fi

    if [ ! -r $1 ];then
        return ${RET_ERR}
    fi
    
    if [ $2 -gt 0 2>/dev/null ];then
        time_limit=$2
    else
        return ${RET_ERR}
    fi

    log_name=$1
    for((i=0,this_time=`date +%s -r $log_name`,last_time=this_time;i<=time_limit;i++))
    do
        if [ $this_time -gt $last_time ];then
            return ${RET_OK}
        fi
        sleep 1
        last_time=$this_time
        this_time=`date +%s -r $log_name`
    done
    return ${RET_ERR}
}

function kill_proc
{
    local proc_name signal_no all_id proc_id father_id
    if [ $# -lt 1 ];then
        return ${RET_ERR}
    elif [ $# -eq 1 ];then
        proc_name=$1
        signal_no=9
    else
        proc_name=$1
        signal_no=$2
    fi
    
    father_id=`ps -eo ppid,comm,cmd|grep " $proc_name"|grep "${BIN_DIR}" |awk '{print $1}'|head -n 1|grep -v "\<1\>"`
    
    if [ ! -z "$father_id" ];then
        kill -9 $father_id 2>/dev/null
    fi

    all_id=`ps -eo ppid,pid,comm,cmd|grep " $proc_name"|grep "${BIN_DIR}" |awk '{printf $1"\n"$2"\n"}'|sort -n|uniq|grep -v "\<1\>"`
    if [ -z "$all_id" ];then
        return ${RET_ERR}
    fi

    for proc_id in $all_id
    do
        kill -${signal_no} $proc_id 2>/dev/null
    done

    return ${RET_OK}
}
